import datetime
import math
import uuid



from flask import Blueprint, request

from app import get_db_connect
from app.common.auth import check_jwt, userSchema, check_auth
from app.common.responses import re_response

bp_users = Blueprint("bp_users", __name__)


# username不能重复
@bp_users.route("/addUsers", methods=[ "POST"])
def users_add():
    if check_auth() > 1:
        print(1)
        return re_response(code=2001,msg="新增失败")
    try:
        useruuid = uuid.uuid1()
        data = request.json
        username = data["username"]
        password = data["password"]
        nickname = data.get("nickname",'')
        role = data["role"]
        mobile = data.get("mobile",'')
        status = data["status"]
        email = data.get("email",'')
        gender = data.get("gender",'0')
        create_time = datetime.datetime.now()

        cursor = get_db_connect().cursor()
        count = cursor.execute("select * from users where username = '%s'" % username)
        if count > 0:
            print(2)
            return re_response(code=2001, msg="新增失败")

        f = cursor.execute('INSERT INTO users (uuid, username,password ,nickname,role,mobile,status,email,gender,create_time) VALUES (%s, %s, %s,%s,%s,%s, %s,%s,%s, %s)',
                           (useruuid, username,password ,nickname,role,mobile,status,email,gender,create_time))
        if f :
            return re_response(msg = "新增成功")
    except Exception as e:
        print(e)
        print(3)
        return re_response(code = 2001 , msg = "新增失败")


@bp_users.route("/getUsers", methods=["GET"])
def users_get():
    username = request.headers.get('username','null')
    if check_auth() > 1:
        return re_response(code=2001, msg="查询失败")
    try:
        connection = get_db_connect()
        with connection.cursor() as cursor:
            page = int(request.args.get('page', 1))
            pageSize = int(request.args.get('pageSize', 10))
            # 跳过这么多条数据，获取当页数据
            offset = (page - 1) * pageSize
            total = cursor.execute('select * from users')
            # 总页数
            pages = math.ceil(total / pageSize)
            if not username:
                count = cursor.execute("SELECT * FROM users LIMIT %s OFFSET %s" % (pageSize, offset))
                user_data = cursor.fetchall()
            else:
                count = cursor.execute("SELECT * FROM users where username like '%s'LIMIT %s OFFSET %s " % ( f"%{username}%",pageSize, offset))
                user_data = cursor.fetchall()
            schema = userSchema(many=True)
            user_data = schema.dump(user_data)
        connection.close()
        return re_response( msg = "查询成功",data=user_data)
    except Exception as e:
        print(e)
        return re_response(code = 2001 , msg = "查询失败")

@bp_users.route("/updateUsers", methods=[ "POST"])
def users_update():
    data = request.json
    # 用username,
    username= data['username']
    if check_auth() :
        return re_response(code=2001, msg="更新失败")
    try:
        cursor = get_db_connect().cursor()
        f = cursor.execute("select * from users where username = '%s'" % username)
        user_data = cursor.fetchall()[0]
        if not f :
            return re_response(code=2001, msg="更新失败")

        nickname = data.get("nickname", user_data['nickname'])
        role = data.get("role",user_data['role'])
        mobile = data.get("mobile", user_data['mobile'])
        status = data.get("status", user_data['status'])
        email = data.get("email", '')
        cursor.execute("update users  set nickname='%s', role='%s',mobile='%s',status='%s',email='%s' where username = '%s'" % (nickname,role,mobile,status,email,username))
        return re_response(msg="更新成功")
    except Exception as e:
        print(e)
        return re_response(code=2001, msg="更新失败")


@bp_users.route("/deleteUsers", methods=[ "POST"])
def users_delete():

    if check_auth() > 1:
        return re_response(code=2001, msg="删除失败")
    data = request.json
    # username,不是useruuid
    data = eval(data.get('username'))
    try:
        cursor = get_db_connect().cursor()
        for username in data:
            f = cursor.execute("select * from users where username = '%s'" % username)
            user_data = cursor.fetchall()
            if not f:
                return re_response(code=2001, msg="删除失败")
        for username in data:
            cursor.execute("DELETE  from users where username='%s'" % username)
        return re_response(msg="删除成功")
    except Exception as e:
        print(e)
        return re_response(code=2001, msg="删除失败")